/*
 Copyright 2012 Jason Drake (jadrake75@gmail.com)
 
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
 
 http://www.apache.org/licenses/LICENSE-2.0
 
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */


package org.javad.pdf.util;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.ByteArrayOutputStream;
import java.util.StringTokenizer;
import org.javad.pdf.IContentGenerator;
import org.javad.pdf.OutputBounds;

public class PdfUtil {

    public static float DPI = 72.0f;
    public static float MM_INCH = 25.4f;

    public static float convertFromMillimeters(float mm) {
        return mm / MM_INCH * DPI;
    }

    public static boolean isTextTooWide(String text, Font f, float width) {
        return f.getBaseFont().getWidthPoint(text, f.getSize()) > width;
    }

    /**
     * Convert the string to a Proper Case String
     *
     * @param s
     * @return
     */
    public static String convertToProperCase(String s) {
        StringBuilder buf = new StringBuilder(s.length());
        StringTokenizer t = new StringTokenizer(s, " ", true);
        while (t.hasMoreTokens()) {
            String token = t.nextToken();
            String remainder = (token.length() > 1) ? token.substring(1).toLowerCase() : token;
            if (token.length() > 1) {
                buf.append(("" + token.charAt(0)).toUpperCase());
            }
            buf.append(remainder);

        }
        return buf.toString();
    }

    /**
     * Whether the text represents an issue Text string.
     * 
     * @param s
     * @return 
     */
    @SuppressWarnings("null")
    public static boolean isIssueText(String s) {
        boolean valid = (s != null && !s.isEmpty());
        if (valid) {
            for (int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                if (!Character.isDigit(c) && c != '-') {
                    valid = false;
                }
            }
        }
        return valid;
    }

    public static float renderConstrainedText(PdfContentByte content, String text, Font f, float x, float y, int width) {
        float offset = 0.0f;
        if (text == null || text.isEmpty()) {
            return offset;
        }
        float w = PdfUtil.convertFromMillimeters(width) * .95f;
        content.setFontAndSize(f.getBaseFont(), f.getSize());
        f.getBaseFont();

        String prevStr = "";
        text = text.replace("\\n", "\n");
        for (String v : text.split("\n")) {
            String str = "";
            for (String s : v.split(" ")) {
                str += ((!str.isEmpty()) ? " " : "") + s;
                if (isTextTooWide(str, f, w)) {
                    content.showTextAligned(PdfContentByte.ALIGN_CENTER, prevStr, x, y + offset, 0.0f);
                    offset -= f.getSize() + 1;
                    prevStr = s;
                    str = s;
                    continue;
                }
                prevStr = str;
            }
            if (!str.isEmpty()) {
                content.showTextAligned(PdfContentByte.ALIGN_CENTER, prevStr, x, y + offset, 0.0f);
                offset -= f.getSize() + 1;
            }
        }

        return offset;
    }

    public static float findMaximumWidth(IContentGenerator generator, PdfContentByte content) {
        float width = 0.0f;
        try {
            Document d = new Document(content.getPdfDocument().getPageSize());
            PdfWriter writer = PdfWriter.getInstance(d, new ByteArrayOutputStream());
            d.open();
            PdfContentByte c = writer.getDirectContent();
            OutputBounds bounds = generator.generate(c);
            width = bounds.width;
            d.close();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return width;
    }

}
